<template>
  <div>
    <el-dialog :visible.sync="visibleLocal" :before-close="handleClose" top="15%" width="31%"
      :close-on-click-modal="false">
      <template #title>
        <div class="addDataBtnBox" @click="addDataBtn" style="z-index: 999; cursor: pointer">
          <i class="el-icon-check" />
        </div>
        <p class="dialog-title">页面链接</p>
      </template>

      <div class="edit-panorama-body" style="height: 400px">
        <!-- 按钮模板 -->
        <div class="upload-name-box">
          <p class="panorama-name" style="align-self: flex-start;margin-top: 20px;">按钮模板：</p>
          <div style="width: 85%; height: 200px;">
            <div style="
              width: 100%;
              height: 200px;
              display: flex;
              justify-content: space-between;
              align-items: center;
              flex-wrap: wrap;
            ">
              <img v-for="(img, index) in templates" :key="index" :src="img" @click="selectTemplate(index)"
                :class="{ selected: selectedIndex === index }" style="width: 100px; height: 30px; cursor: pointer;" />
            </div>
          </div>
        </div>

        <!-- 上传图片 -->
        <div class="upload-name-box" style="margin-top: 20px;">
          <p class="panorama-name">按钮尺寸：</p>
          <el-input v-model="kuan" size="mini" style="width: 15%; margin-left: 5px" placeholder="宽度" />×
          <el-input v-model="gao" size="mini" style="width: 15%; " placeholder="高度" />
        </div>

        <!-- 上传图片 -->
        <div class="upload-name-box" style="margin-top: 20px;">
          <p class="panorama-name">上传按钮图片：</p>
          <input type="file" ref="fileInput" @change="handleFileChange" accept="image/*" />
          <span v-if="hasFile" class="remove-btn" @click="removeFile">×</span>
        </div>

        <div class="upload-name-box" style="margin-top: 20px;">
          <p class="panorama-name">选择界面：</p>
          <button size="mini" @click="selectWeb = true" class="btn-sel">选择</button>
          <span style="margin-left: 5px;">{{ webname }}</span>
        </div>

        <!-- 选择界面 -->
        <div class="upload-name-box" style="margin-top: 10px;">
          <p class="panorama-name">按钮名称：</p>
          <el-input v-model="btnName" size="mini" style="width: 25%; margin-left: 5px" />
          <p class="panorama-name" style="margin-left: 30px;">按钮文字大小/颜色：</p>
          <el-input v-model="nameSize" size="mini" style="width: 15%; margin-left: 5px" />
          <el-color-picker v-model="color" style="width: 15%; margin-left: 15px; margin-top: 3px;"></el-color-picker>
        </div>

        <!-- 按钮名称 -->
        <!-- <div class="upload-name-box" style="margin-top: 20px;">
        <p class="panorama-name">按钮名称：</p>
        <el-input v-model="btnName" size="mini" style="width: 40%; margin-left: 5px" />
      </div> -->
      </div>
    </el-dialog>

    <el-dialog title="选择页面" :visible.sync="selectWeb" :before-close="handleCloseSelectWeb" top="15%" width="31%"
      :close-on-click-modal="false">
      <template #title>
        <div class="addDataBtnBox" @click="handleCloseSelectWeb" style="z-index: 999; cursor: pointer">
          <i class="el-icon-check" />
        </div>
        <p class="dialog-title">选择页面</p>
      </template>
      <div style="height: 400px;">
        <el-tree :data="treeLevelData" :props="defaultProps" @node-click="handleNodeClick"
          style="max-height: 380px; overflow: auto;"></el-tree>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRightTree, savePageLink } from "../../api/cad.js"
export default {
  name: "MyDialog",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      visibleLocal: this.visible,
      color: "#ffffff",
      btnName: "",
      nameSize: "",
      selectedIndex: null,
      hasFile: false, // 用来判断是否有文件
      templates: [
        require("../../assets/btn/1.png"),
        require("../../assets/btn/2.png"),
        require("../../assets/btn/3.png"),
        require("../../assets/btn/4.png"),
        require("../../assets/btn/5.png"),
        require("../../assets/btn/6.png"),
        require("../../assets/btn/7.png"),
        require("../../assets/btn/8.png"),
        require("../../assets/btn/9.png"),
        require("../../assets/btn/10.png"),
        require("../../assets/btn/11.png"),
        require("../../assets/btn/12.png"),
      ],
      selectWeb: false,
      treeLevelData: [],
      defaultProps: { children: 'child', label: 'name' },
      nodeData: {},
      webname: "未选择任何界面",
      kuan: '',
      gao: '',
      updateBtnData: {},
      treeLevelData: [],
      updataBox: false,
      title: "页面链接",
      filedata: null,
      uploadedFileUrl: ''
    };
  },
  watch: {
    visible(val) {
      this.visibleLocal = val;
      this.getTreeData()
    },
    visibleLocal(val) {
      this.$emit("update:visible", val);
    },
  },
  methods: {
    handleClose() {
      this.visibleLocal = false;
    },
    handleFileChange(event) {
      const file = event.target.files[0];
      this.filedata = event.target.files[0];
      if (file) {
        this.hasFile = true;
        this.uploadedFileUrl = URL.createObjectURL(file);
      }
    },
    removeFile() {
      // 重置 input
      this.$refs.fileInput.value = "";
      this.hasFile = false;
    },
    selectTemplate(index) {
      this.selectedIndex = index;
    },
    handleCloseSelectWeb() {
      this.selectWeb = false;
    },
    handleNodeClick(data) {
      this.nodeData = data
      this.webname = data.name
    },
    getTreeData() {
      getRightTree().then(res => {
        this.treeLevelData = res.data
      })
    },
    addDataBtn() {
      if (this.updataBox) {
        // 修改数据
        let saveBtnObj = new FormData();
        saveBtnObj.set('template', this.selectedIndex + 1);
        saveBtnObj.set('name', this.btnName);
        saveBtnObj.set('size', this.nameSize);
        saveBtnObj.set('y', this.updateBtnData.y);
        saveBtnObj.set('x', this.updateBtnData.x);
        saveBtnObj.set('color', this.color);
        //saveBtnObj.set('file', "");
        saveBtnObj.set('height', this.gao);
        saveBtnObj.set('width', this.kuan);
        saveBtnObj.set('currentCadTreeId', this.updateBtnData.currentCadTreeId);
        saveBtnObj.set('targetCadTreeId', this.updateBtnData.targetCadTreeId);
        saveBtnObj.set('id', this.updateBtnData.id);
        if (this.hasFile) {
          saveBtnObj.set('file', this.filedata);
        }
        savePageLink(saveBtnObj).then(res => {
          this.$message.success(res.data);
          this.$emit('select-btn');
        })
        this.updataBox = false
        this.visibleLocal = false;
      } else {
        this.updataBox = false
        if (this.hasFile) {
          let btnData = {
            width: this.kuan,
            height: this.gao,
            name: this.btnName,
            template: this.selectedIndex + 1,
            color: this.color,
            size: this.nameSize,
            nodeData: this.nodeData,
            file: this.filedata,
            fileUrl: this.uploadedFileUrl
          }
          this.$emit('add-btn', btnData)
        } else {
          let btnData = {
            width: this.kuan,
            height: this.gao,
            name: this.btnName,
            template: this.selectedIndex + 1,
            color: this.color,
            size: this.nameSize,
            nodeData: this.nodeData,
          }
          // 这里列出必须填写的字段，后面要用 key 来检验
          const requiredFields = ['width', 'height', 'name', 'template', 'color', 'size', 'nodeData'];
          for (const key of requiredFields) {
            const value = btnData[key];
            // null、undefined、空字符串 都算没填
            if (value === null || value === undefined || value === '' || (key === 'nodeData' && Object.keys(value).length === 0)) {
              this.$message.warning('请将信息填写完整！');
              return;
            }
          }
          this.$emit('add-btn', btnData)
        }

        this.visibleLocal = false;
      }

    },
    updateBtn(btn, tree) {
      this.treeLevelData = tree
      const node = this.findNodeById(btn.targetCadTreeId);
      this.visibleLocal = true
      this.updateBtnData = btn
      this.kuan = btn.width
      this.gao = btn.height
      this.selectedIndex = btn.template - 1
      this.webname = node.name
      this.color = btn.color
      this.nameSize = btn.size
      this.btnName = btn.name
      this.updataBox = true
    },
    // 查询node
    findNodeById(id, nodes = this.treeLevelData) {
      for (const node of nodes) {
        if (node.id == id) {
          return node;
        } else if (node.child && node.child.length) {
          const found = this.findNodeById(id, node.child);
          if (found) {
            return found;
          }
        }
      }
      return null;
    },
    // 添加按钮将参数值改为false
    addBtn() {
      this.updataBox = false
      this.kuan = ""
      this.gao = ""
      this.selectedIndex = 1
      this.webname = "未选择任何界面"
      this.color = "#ffffff"
      this.nameSize = ""
      this.btnName = ""
    }
  },
  mounted() {
    this.getTreeData()
  }
};
</script>

<style scoped>
.addDataBtnBox {
  margin-right: 15px;
  position: absolute;
  top: 10px;
  right: 32px;
  cursor: pointer;
}

.dialog-title {
  font-size: 11px;
  color: #ffffff;
}

.upload-name-box {
  margin-top: 10px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  font-size: 11px;
  color: #fbfbfb;
}

.selected {
  border: 1px solid #006aff;
  box-shadow: 0 0 10px #006aff;
  box-sizing: border-box;
}

.remove-btn {
  margin-left: 8px;
  cursor: pointer;
  color: #ff4d4f;
  font-size: 18px;
  font-weight: bold;
  line-height: 1;
}

.el-tree {
  max-height: 400px;
  overflow: auto;
}

.el-tree::-webkit-scrollbar {
  width: 8px;
}

.el-tree::-webkit-scrollbar-track {
  background: #8d8d8d;
  border-radius: 4px;
}

.el-tree::-webkit-scrollbar-thumb {
  background: #3c3c3c;
  border-radius: 4px;
}

.el-tree::-webkit-scrollbar-thumb:hover {
  background: #66b1ff;
}

input[type="file"] {
  font-size: 11px;
  /* 改的是「未选择任何文件」这段文字 */
}

input[type="file"]::file-selector-button {
  font-size: 11px;
  /* 改的是按钮文字 */
  padding: 2px 8px;
  /* 可选：缩小按钮 */
}

.btn-sel {
  font-size: 11px;
}
</style>
